import {ref} from 'vue';

import {useRouter} from 'vue-router';

import {defineStore} from 'pinia';

import {notification} from 'ant-design-vue';

import type {Recordable} from '#/typings';

import {resetAllStores, useAccessStore, useUserStore} from '#/stores';

import {DEFAULT_HOME_PATH, LOGIN_PATH} from '#/constants';

import {$t} from '#/locales';

import {getAuthentication, login, logout} from '#/api/core/auth';

export const useAuthStore = defineStore('core-auth', () => {
    const accessStore = useAccessStore();
    const userStore = useUserStore();
    const router = useRouter();

    const loginLoading = ref(false);

    async function authLogin(params: Recordable<any>, onSuccess?: () => Promise<void> | void,) {
        let userInfo: null;

        try {
            loginLoading.value = true;

            const accessToken = await login(params);

            if (accessToken) {
                accessStore.setAccessToken(accessToken);

                const [authentication] = await Promise.all([
                    getAuthentication(),
                ]);

                userInfo = authentication;

                userStore.setUserInfo(authentication);
                accessStore.setAccessRoles(authentication?.roles);
                accessStore.setAccessCodes(authentication?.codes);

                if (accessStore.loginExpired) {
                    accessStore.setLoginExpired(false);
                } else {
                    onSuccess ? await onSuccess?.() : await router.push(DEFAULT_HOME_PATH);
                }

                if (userInfo?.nickname) {
                    notification.success({
                        description: `${$t('authentication.loginSuccessDesc')}: ${userInfo?.nickname}`,
                        duration: 3,
                        message: $t('authentication.loginSuccess'),
                    });
                }
            }
        } finally {
            loginLoading.value = false;
        }

        return {
            userInfo,
        }
    }

    async function authLogout(redirect: boolean = true) {
        try {
            await logout();
        } catch {
        }

        resetAllStores();
        accessStore.setLoginExpired(false);

        // 回登录页带上当前路由地址
        await router.replace({
            path: LOGIN_PATH,
            query: redirect ? {redirect: encodeURIComponent(router.currentRoute.value.fullPath),} : {},
        });
    }

    async function authenticationInfo() {
        const authentication = await getAuthentication();
        userStore.setUserInfo(authentication);
        accessStore.setAccessRoles(authentication?.roles);
        accessStore.setAccessCodes(authentication?.codes);
        return authentication;
    }

    function $reset() {
        loginLoading.value = false;
    }

    return {
        $reset,
        authLogin,
        authLogout,
        loginLoading,
        authenticationInfo,
    };
});